package com.netintech.intelligenceInterface.iflytek.controller;

import com.netintech.intelligenceInterface.iflytek.domain.offlineTranscribe.AudioFileTranscribeParam;
import com.netintech.intelligenceInterface.iflytek.util.HeadersUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

import static com.netintech.intelligenceInterface.common.StaticBean.URL1;

/**
 * @author lining
 * @date 2021/4/26 14:41
 * 离线转写 接口
 * 文件转写
 */
@RestController
public class OfflineTranscribeController {

    @Autowired
    private RestTemplate restTemplate;

    private static final String AUDIO_FILE_OFFLINE_TRANSCRIBE_URL = "/tuling/asr/v21/processFile/";

    @PostMapping("offlineTranscribe")
    public String processFile(AudioFileTranscribeParam param) throws IOException {
        return getAudioFileOfflineTranscribeResult(param);
    }

    @PostMapping("/test/offlineTranscribe")
    public String processFileTest(AudioFileTranscribeParam param) throws IOException {
        return getAudioFileOfflineTranscribeResult(param);
    }

    private String getAudioFileOfflineTranscribeResult(AudioFileTranscribeParam param) throws IOException {
        String url = URL1 + AUDIO_FILE_OFFLINE_TRANSCRIBE_URL + param.getTrackId();
        MultipartFile multipartFile = param.getAudioFile();
        ByteArrayResource fileAsResource = new ByteArrayResource(multipartFile.getBytes()) {
            @Override
            public String getFilename() {
                return multipartFile.getOriginalFilename();
            }
            @Override
            public long contentLength() {
                return multipartFile.getSize();
            }
        };
        MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
        multipartRequest.add("audioFile", fileAsResource);
        multipartRequest.add("lang", param.getLang());
        multipartRequest.add("props", param.getProps());
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(multipartRequest, HeadersUtil.getMultiHeader(url));
        ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
        return response.getBody();
    }
}
